package com.atguigu.guli.service.oss.service.impl;

import com.atguigu.guli.service.oss.entity.ImageDao;
import com.atguigu.guli.service.oss.mapper.LocalFileMapper;
import com.atguigu.guli.service.oss.service.LocalFileService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

/**
 * @author jack
 * date 2024-07-02 11:23
 */
@Service
@Slf4j
public class LocalFileServiceImpl implements LocalFileService {
    @Resource
    private LocalFileMapper localFileMapper;
    @Override
    public String upload(byte[] bytes, String module, String originalFilename) {
        // 生成图片主键id
        Long id = System.currentTimeMillis();
        String imageUrl = String.format("/admin/oss/file/getImage/%s/%s", id, originalFilename);

        int num = localFileMapper.insertImage(new ImageDao(id, module, originalFilename, imageUrl, bytes));

        return imageUrl;
    }

    @Override
    public void removeFile(String url) {
        int num = localFileMapper.removeFile(url);
        if (num > 0) {
            log.info("文件删除成功");
        } else {
            log.info("文件删除失败");
        }
    }

    @Override
    public ResponseEntity<Object> getImage(Long id, String fileName) {
        try {
            ImageDao imageDao = localFileMapper.selectImageById(id);
            MediaType mediaType = MediaType.parseMediaType(Files.probeContentType(Paths.get(fileName)));
            return ResponseEntity.ok()
                    .contentType(mediaType)
                    .body(imageDao.getBlobData());
        } catch (IOException e) {
            log.error("加载图片出错", e);
            throw new RuntimeException(e);
        }
    }
}
